//
//  ToolsClass.m
//  jobClient
//
//  Created by 一览OS on 2020/7/16.
//  Copyright © 2020 YL1001. All rights reserved.
//

#import "ToolsClass.h"

@implementation ToolsClass
#pragma mark - 设置单边底线
+(void)setBorderWithView:(UIView *)view top:(BOOL)top left:(BOOL)left bottom:(BOOL)bottom right:(BOOL)right borderColor:(UIColor *)color borderWidth:(CGFloat)width
{
    if (top) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (left) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (bottom) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, view.frame.size.height - width, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (right) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(view.frame.size.width - width, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
}


#pragma mark - 字符串文字的长度
+(CGFloat)widthOfString:(NSString *)string font:(UIFont*)font height:(CGFloat)height
{
    if (!string || string.length == 0) {
        return 0.0;;
    }
//    NSStringDrawingUsesLineFragmentOrigin |  NSStringDrawingUsesFontLeading
    
    NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dict context:nil];
    
    
    return ceil(rect.size.width);
}

+(CGFloat)widthOfString:(NSString *)string attribute:(NSDictionary*)attribute height:(CGFloat)height
{
    
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attribute context:nil];
    
    return ceil(rect.size.width);
    
}

#pragma mark - 字符串文字的高度
+(CGFloat)heightOfString:(NSString *)string font:(UIFont*)font width:(CGFloat)width
{
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:parameterDict context:nil];
    
    return ceil(rect.size.height);
}

#pragma mark - 字符串文字的高度
+(CGFloat)heightOfString:(NSString *)string attribute:(NSDictionary*)attribute width:(CGFloat)width
{
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attribute context:nil];
    
    return ceil(rect.size.height);
}

#pragma mark - UILabel字体颜色大小
+ (void)fuwenbenLabel:(UILabel *)label FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    label.attributedText = str;
}

#pragma mark - 获取URL中的参数
+ (NSDictionary *)getParametersWithUrlString:(NSString *)urlString {

    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];

    //获取问号的位置，问号后是参数列表
    NSRange range = [urlString rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return tempDic;
    }
    //获取参数列表
    NSString *propertys = [urlString substringFromIndex:(int)(range.location+1)];
    //进行字符串的拆分，通过&来拆分，把每个参数分开
    NSArray *subArray = [propertys componentsSeparatedByString:@"&"];
    //把subArray转换为字典
    //tempDic中存放一个URL中转换的键值对
    if (subArray.count > 0) {

        for (int j = 0 ; j < subArray.count; j++) {

            //在通过=拆分键和值
            NSArray *dicArray = [subArray[j] componentsSeparatedByString:@"="];
            //给字典加入元素
            [tempDic setObject:dicArray[1] forKey:dicArray[0]];
        }
    }
    NSLog(@"打印URL的参数列表生成的字典：\n%@", tempDic);
    return tempDic;
}

#pragma mark - 替换手机中间4位
+ (NSString *)replacePhoneMiddleWithPhoneNumber:(NSString *)number {
    
    NSMutableString * phoneNumber = [NSMutableString stringWithString:number];
    NSRange range;
    range.location = 3;
    range.length = 4;
    [phoneNumber replaceCharactersInRange:range withString:@"****"];
    return phoneNumber;
}
// 高清截屏
+ (UIImage *)currentViewScreenPhoto:(UIView *)topView
{

    @autoreleasepool {
        if ([topView isKindOfClass:UIScrollView.class]) {
            UIImage*image  = nil;
            UIScrollView *scrollView = (UIScrollView *)topView;
            CGPoint savedContentOffset = scrollView.contentOffset;
            CGRect savedFrame = scrollView.frame;
            CGSize contentSize = scrollView.contentSize;
            CGRect oldBounds = scrollView.layer.bounds;
            if(@available(iOS 13.0, *)){
                [scrollView.layer setBounds:CGRectMake(oldBounds.origin.x, oldBounds.origin.y,contentSize.width, contentSize.height)];
            }
            UIGraphicsBeginImageContext(scrollView.contentSize);
            scrollView.contentOffset = CGPointZero;
            scrollView.frame=CGRectMake(0,0,contentSize.width, contentSize.height);
            [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
            if(@available(iOS 13.0, *)){
                [scrollView.layer setBounds:oldBounds];
            }
            image = UIGraphicsGetImageFromCurrentImageContext();
            scrollView.contentOffset= savedContentOffset;
            scrollView.frame= savedFrame;
            UIGraphicsEndImageContext();
            return image;
        }else{
            // 高清截屏
            UIGraphicsBeginImageContextWithOptions(topView.bounds.size, NO, 0.0);
            [topView.layer renderInContext:UIGraphicsGetCurrentContext()];
            // 保存为图片
            UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return viewImage;
        }
    
    }
}

+(UIViewController *)currentViewController:(UIView *)view{

    /// Finds the view's view controller.

    // Traverse responder chain. Return first found view controller, which will be the view's view controller.

    UIResponder *responder = view;

    while ((responder = [responder nextResponder]))

        if ([responder isKindOfClass: [UIViewController class]])

            return (UIViewController *)responder;

    // If the view controller isn't found, return nil.

    return nil;

}

+ (UIViewController*)EL_currentViewController{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *topViewController = [window rootViewController];
    if (topViewController.presentedViewController) {
        topViewController = topViewController.presentedViewController;
    } else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
        topViewController = [(UINavigationController *)topViewController topViewController];
    } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab = (UITabBarController *)topViewController;
        topViewController = tab.selectedViewController;
    }
    return topViewController;
}

/**
 比较两个版本号的大小
 
 @param v1 第一个版本号
 @param v2 第二个版本号
 @return 版本号相等,返回0; v1小于v2,返回-1; 否则返回1.
 */
+ (NSInteger)compareVersion:(NSString *)v1 to:(NSString *)v2 {
    // 都为空，相等，返回0
    if (!v1 && !v2) {
        return 0;
    }
    
    // v1为空，v2不为空，返回-1
    if (!v1 && v2) {
        return -1;
    }
    
    // v2为空，v1不为空，返回1
    if (v1 && !v2) {
        return 1;
    }
    
    // 获取版本号字段
    NSArray *v1Array = [v1 componentsSeparatedByString:@"."];
    NSArray *v2Array = [v2 componentsSeparatedByString:@"."];
    // 取字段最少的，进行循环比较
    NSInteger smallCount = (v1Array.count > v2Array.count) ? v2Array.count : v1Array.count;
    
    for (int i = 0; i < smallCount; i++) {
        NSInteger value1 = [[v1Array objectAtIndex:i] integerValue];
        NSInteger value2 = [[v2Array objectAtIndex:i] integerValue];
        if (value1 > value2) {
            // v1版本字段大于v2版本字段，返回1
            return 1;
        } else if (value1 < value2) {
            // v2版本字段大于v1版本字段，返回-1
            return -1;
        }
        
        // 版本相等，继续循环。
    }
    
    // 版本可比较字段相等，则字段多的版本高于字段少的版本。
    if (v1Array.count > v2Array.count) {
        return 1;
    } else if (v1Array.count < v2Array.count) {
        return -1;
    } else {
        return 0;
    }
    
    return 0;
}

//存储（NSKeyedArchiver，防止出现value为空无法直接存储的情况）
+ (void)EL_saveDict:(id)vaule key:(NSString *)key{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:vaule];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

//获取存储数据
+ (id) EL_getSaveDictWithkey:(NSString *)key{

    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    id vaule = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return vaule;
}

#pragma mark - 颜色转换 iOS中十六进制的颜色转换为UIColor

+ (UIColor *) colorWithHexString: (NSString *)hexString
{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    //hexString应该6到8个字符
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    //如果hexString 有@"0X"前缀
    if ([cString hasPrefix:@"0X"] || [cString hasPrefix:@"0x"])
        cString = [cString substringFromIndex:2];
    
    
    //如果hexString 有@"#""前缀
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    //RGB转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //R
    NSString *rString = [cString substringWithRange:range];
    
    //G
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //B
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    //
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

+ (NSString *)howLongTimeAgoWithTimeStamp:(NSString *)timeStamp
{
    NSString *timeStr = @"刚刚";
    long interval = [[NSDate date] timeIntervalSince1970] - [timeStamp longLongValue];
    long months = interval / (30 * 24 * 60 * 60),
         days = interval / (24 * 60 * 60),
         hours = interval / (60 * 60),
         minutes = interval / 60;
    
//    else if(months > 0){
//    timeStr = [NSString stringWithFormat:@"%ld个月前",months];
//}
    if (months > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStamp integerValue]];
        timeStr = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    }else if (days > 0){
        timeStr = [NSString stringWithFormat:@"%ld天前",days];
    }else if (hours > 0){
        timeStr = [NSString stringWithFormat:@"%ld小时前",hours];
    }else if (minutes > 5){
        timeStr = [NSString stringWithFormat:@"%ld分钟前",minutes];
    }else{
        timeStr = @"刚刚";
    }
    return timeStr;
}

//时间戳变为格式时间
+ (NSString *)timeConvertStrToTime:(NSString *)timeStr withFormatter:(NSString *)dateFormat

{
    long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    //    long long time=[timeStr longLongValue] / 1000;

    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

    [formatter setDateFormat:dateFormat];//@"yyyy-MM-dd"

    NSString*timeString=[formatter stringFromDate:date];

    return timeString;
    
}

//获取当前时间字符串
+(NSString*)getCurrentTimeswithFormatter:(NSString *)dateFormat{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    [formatter setDateFormat:dateFormat];

    //现在时间,你可以输出来看下是什么格式

    NSDate *datenow = [NSDate date];

    //----------将nsdate按formatter格式转成nsstring

    NSString *currentTimeString = [formatter stringFromDate:datenow];

    NSLog(@"currentTimeString =  %@",currentTimeString);

    return currentTimeString;

}


/**
 绘制图片
 
 @param color 背景色
 @param size 大小
 @param text 文字
 @param textAttributes 字体设置
 @param isCircular 是否圆形
 @return 图片
 */
+ (UIImage *)zd_imageWithColor:(UIColor *)color
                          size:(CGSize)size
                          text:(NSString *)text
                textAttributes:(NSDictionary *)textAttributes
                      circular:(BOOL)isCircular
{
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // circular
    if (isCircular) {
        CGPathRef path = CGPathCreateWithEllipseInRect(rect, NULL);
        CGContextAddPath(context, path);
        CGContextClip(context);
        CGPathRelease(path);
    }
    
    // color
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    
    // text
    CGSize textSize = [text sizeWithAttributes:textAttributes];
    [text drawInRect:CGRectMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2, textSize.width, textSize.height) withAttributes:textAttributes];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//判断是否为浮点形：

+ (BOOL)isPureFloat:(NSString*)string{

    NSScanner* scan = [NSScanner scannerWithString:string];

    float val;

    return[scan scanFloat:&val] && [scan isAtEnd];

}

//压缩图片
+ (UIImage *)compressWith:(UIImage *)image imageMaxLength:(NSInteger)imageMaxLength{
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    //NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);
    if (data.length < imageMaxLength) return [UIImage imageWithData:data];
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        //NSLog(@"Compression = %.1f", compression);
        //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
        if (data.length < imageMaxLength * 0.9) {
            min = compression;
        } else if (data.length > imageMaxLength) {
            max = compression;
        } else {
            break;
        }
    }
    // NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);
    if (data.length < imageMaxLength) return [UIImage imageWithData:data];
    UIImage *resultImage = [UIImage imageWithData:data];
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > imageMaxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)imageMaxLength / data.length;
        //NSLog(@"Ratio = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        // NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);
    }
    //NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);
    return [UIImage imageWithData:data];
}

//字符串提取URL
+ (NSArray*)getURLFromStr:(NSString *)string {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,4})(:\d+)?(/[a-zA-Z0-9\.\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,4})(:\d+)?(/[a-zA-Z0-9\.\-~!@#$%^&*+?:_/=<>]*)?)";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
    options:NSRegularExpressionCaseInsensitive
    error:&error];

    NSArray *arrayOfAllMatches = [regex matchesInString:string
    options:0
    range:NSMakeRange(0, [string length])];

    //NSString *subStr;
    NSMutableArray *arr=[[NSMutableArray alloc] init];

    for (NSTextCheckingResult *match in arrayOfAllMatches){
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    return arr;
}

//字符串是否包含URL
+ (BOOL )isContainsURLFromStr:(NSString *)string {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,4})(:\d+)?(/[a-zA-Z0-9\.\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,4})(:\d+)?(/[a-zA-Z0-9\.\-~!@#$%^&*+?:_/=<>]*)?)";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
    options:NSRegularExpressionCaseInsensitive
    error:&error];

    NSArray *arrayOfAllMatches = [regex matchesInString:string
    options:0
    range:NSMakeRange(0, [string length])];

    //NSString *subStr;
    NSMutableArray *arr=[[NSMutableArray alloc] init];

    for (NSTextCheckingResult *match in arrayOfAllMatches){
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    
    if (arr && arr.count > 0) {
        return YES;
    }
    return NO;
}

@end
